package com.bootdo.system.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import com.BootdoApplication;
import com.blade.kit.json.JSONObject;
import com.bootdo.BeanHelper;
import com.bootdo.system.dao.WxMsgDao;
import com.bootdo.system.domain.WxMsgDO;
import com.bootdo.system.service.WxMsgService;
import com.wechat.util.AbstractMessageHandler;
import com.wechat.util.PipeLineManager;
import com.wechat.util.WechatMeta;
import com.wechat.util.WxLocalCache;
import com.wechat.util.Enums.MsgType;

public class TxtMessageHandler extends AbstractMessageHandler {

	private static final Logger LOGGER = LoggerFactory.getLogger(TxtMessageHandler.class);

	// private AccountConfigDao accountConfigDao = new AccountConfigDao();
	
	

	public TxtMessageHandler(WechatMeta meta) {
		super(meta);
		this.meta = meta;
	}

	@Override
	public void process(JSONObject msg) {
		String content = msg.getString("Content");
		LOGGER.info("content:{}", content);
		if (!preHandle(msg)) {
			return;
		}

		String fromUserName = msg.getString("FromUserName");
		String fromNickName = getUserRemarkName(fromUserName);
		String selftName = getSelfNickName();
		String[] contentArray = content.split(":");
		if (contentArray.length == 0 || contentArray.length == 1) {
		} else {
			content = contentArray[1].replace("<br/>", "\n");
		}
		PipeLineManager.instance().process(meta, fromNickName + "-" + selftName + ":" + content, MsgType.TXT);
		// String autoReplay = accountConfigDao.selectOne(meta.getMobile(),
		// AccountConfig.NAME_AUTO_REPLAY);
		// if (!AccountConfig.ON.equals(autoReplay)) {
		// LOGGER.warn("auto reply setting was off,you can switch on it");
		// return;
		// }
		String ans = reply(fromUserName, content); 
		System.out.println("ans:======>"+ans+"[]"+msg.getString("FromUserName"));

		
		try{
			WxMsgService wxMsgService = BeanHelper.getBean("wxMsgService", WxMsgService.class);
					
			
			JSONObject contact = WxLocalCache.instance().getContactByUserName(fromUserName);
			
			WxMsgDO wxMsgDo = new WxMsgDO();
			wxMsgDo.setFromusername(contact.getString("NickName", "[无名氏]"));
			wxMsgDo.setMsgContent(content);
			wxMsgService.save(wxMsgDo);
			
			
		}catch (Exception e) {
			System.out.println("保存消息异常:"+e.getMessage() );
		}
		
		
		webwxsendmsg(ans, msg.getString("FromUserName"));
		PipeLineManager.instance().process(meta, selftName + "-" + fromNickName + "：" + ans, MsgType.TXT);
	} 

}
